class websocketUtils {
  constructor(option = {}) {
    this.uniCloudWs = option.url || 'ws-chat'
    this.socketTask = null
  }

  async init(id, bol = true) {
    try {
      bol && (await this.close())
      this.socketTask = await uniCloud.connectWebSocket({
        name: this.uniCloudWs,
        query: { id },
        success: () => {
          console.log('初始化连接成功')
        },
        fail: (err) => {
          console.log('初始化连接失败', err)
        },
      })
      this.socketTask.onOpen = this.onOpen
      this.socketTask.onClose = this.onClose
      this.socketTask.onError = this.onError
      this.socketTask.onMessage = this.onMessage
    } catch (error) {
      uni.showToast({
        title: '初始化错误',
        icon: 'error',
        duration: 2000,
      })
    }
  }
  sendMsg(data) {
    return new Promise((resolve, reject) => {
      this.socketTask.send({
        data: data,
        success: resolve,
        fail: reject,
      })
    })
  }
  onMessage(res) {
    console.log('收到ws服务器内容：' + res)
  }

  onOpen() {
    console.log('连接成功')
  }
  onClose(err) {
    console.log('已关闭', err)
  }
  onError(err) {
    console.log('发生错误', err)
  }
  async close() {
    return new Promise((resolve, reject) => {
      this.socketTask &&
        this.socketTask.close({
          success: resolve,
          fail: reject,
        })
      this.socketTask = null
    })
  }
}
